package com.ncpowernode.javaweb;


import com.ncpowernode.javaweb.bean.User;
import com.ncpowernode.javaweb.dao.LoginMapper;
import com.ncpowernode.javaweb.utils.SqlSessionUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        boolean flag = false;// 标志变量，false表示密码错误，true 表示密码正确
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 判断密码是否正确
        SqlSession sqlSession = SqlSessionUtil.openSession();
        LoginMapper mapper = sqlSession.getMapper(LoginMapper.class);
        List<User> users = mapper.selectAll();
        for(User user:users){
            if(user.getUsername().equals(username)&&user.getPassword().equals(password)){
                flag = true;
            }
        }
        String ff = request.getParameter("ff");// 十天免登录的标记
        // 密码的是否正确关系到跳转到的页面
        if(flag){
            if(ff!=null&&ff.equals("1")){
                // 选择了这个标记，选择了十天免登录
                Cookie cookie1 = new Cookie("username",username);
                Cookie cookie2 = new Cookie("password",password);
                //设置Cookie 在硬盘长停留的时间
                cookie1.setMaxAge(60*60*24*10);
                cookie2.setMaxAge(60*60*24*10);
                //设置路径
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                // 响应给浏览器
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            // 会话域中添加数据，证明登录成功，允许访问后面的数据
            User user = new User(null,username,password);
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            response.sendRedirect(request.getContextPath() + "/sucess.html");
        }

    }
}
